package com.scrcu.cloud.wechat.home.endpoint.customer.utils;

import com.alibaba.fastjson.JSONObject;
import com.scrcu.cloud.wechat.home.endpoint.common.utils.RegexUtils;
import com.scrcu.cloud.wechat.home.endpoint.common.utils.StrUtil;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;


public class Http_tool {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Http_tool.class);
    public static String doPost(String url, Object pars, org.slf4j.Logger logger) throws Throwable {
        if (pars == null || StrUtil.isEmpty(url) || !RegexUtils.matchReg(url)) {
            return "检查url或pars是否正确";
        }
        String result = null;
        // CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = HttpPool.getHttpClient();

        HttpPost httpPost = new HttpPost(url);

        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");//必须
        httpPost.addHeader("custNo", "-1");//必须的
        StringEntity se = new StringEntity((String) pars, "UTF-8");
//        System.out.println(se);
        //[Content-Type: text/plain; charset=UTF-8,Content-Length: 77,Chunked: false]

        httpPost.setEntity(se);
        HttpResponse response = httpClient.execute(httpPost);
        int reCode = response.getStatusLine().getStatusCode();
        if (reCode != HttpStatus.SC_OK && httpPost != null) {
            httpPost.abort();
            logger.error("返回非200,状态码:{}", reCode);
        } else {
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return result;
    }

    public static String doPost2(String proxyStr,int proxyPort,String url, Object pars, org.slf4j.Logger logger) throws Throwable {
        if (pars == null || StrUtil.isEmpty(url) || !RegexUtils.matchReg(url)) {
            return "检查url或pars是否正确";
        }
        HttpHost proxy = new HttpHost(proxyStr,proxyPort);
        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();

        String result = null;
        // CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

        HttpPost httpPost = new HttpPost(url);

        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//必须
        StringEntity se = new StringEntity((String) pars, "UTF-8");

        httpPost.setEntity(se);
        HttpResponse response = httpClient.execute(httpPost);
        int reCode = response.getStatusLine().getStatusCode();
        if (reCode != HttpStatus.SC_OK && httpPost != null) {
            httpPost.abort();
            logger.error("返回非200,状态码:{}", reCode);
        } else {
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return result;
    }

    public static JSONObject wechatHttpSend(String data,String url) {
        HttpURLConnection reqConnection = null;
        PrintWriter output = null;
        BufferedReader input =null;
        JSONObject returnJson = null;
        try{
            URL reqUrl = new URL(url);
            reqConnection = (HttpURLConnection) reqUrl.openConnection();
            reqConnection.setInstanceFollowRedirects(true);
            reqConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            reqConnection.setRequestProperty("accept","*/*");
            reqConnection.setDoInput(true);
            reqConnection.setDoOutput(true);
            output = new PrintWriter(reqConnection.getOutputStream());
            output.print(data);
            output.flush();
            StringBuffer sbf = new StringBuffer();
            input  =  new BufferedReader(new InputStreamReader(reqConnection.getInputStream()));
            String str = null;
            while ((str = input.readLine()) !=  null) {
                sbf.append(str);
            }
            returnJson = JSONObject.parseObject(sbf.toString());
            String errorCode = (String) returnJson.get("ec");//返回码ec为"0000000000"代表成功 ，其他为失败

        }catch(Exception e){
            logger.info("发送验证码异常：",e);
        }finally{
            try {
                if(input!=null){
                    input.close();
                }
                if(output!=null){
                    output.close();
                }
                if(reqConnection!=null){
                    reqConnection.disconnect();
                }
            } catch (Exception ex) {
                logger.info("IO流关闭异常",ex);
            }
        }
        return returnJson;
    }

    public static JSONObject wechatHttpSendGet(String proxyStr,int proxyPort,String url) {
        HttpURLConnection reqConnection = null;
        PrintWriter output = null;
        BufferedReader input =null;
        JSONObject returnJson = null;

        try{
            URL reqUrl = new URL(url);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyStr, proxyPort));
            reqConnection = (HttpsURLConnection) reqUrl.openConnection(proxy);
            reqConnection.setInstanceFollowRedirects(true);
            reqConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            reqConnection.setRequestProperty("accept","*/*");
            reqConnection.setDoInput(true);
            reqConnection.setDoOutput(true);
            reqConnection.setRequestMethod("GET");

            StringBuffer sbf = new StringBuffer();
            input  =  new BufferedReader(new InputStreamReader(reqConnection.getInputStream()));
            String str = null;
            while ((str = input.readLine()) !=  null) {
                sbf.append(str);
            }
            returnJson = JSONObject.parseObject(sbf.toString());
            String errorCode = (String) returnJson.get("ec");//返回码ec为"0000000000"代表成功 ，其他为失败

        }catch(Exception e){
            logger.info("获取腾讯openid返回报文异常：",e);
        }finally{
            try {
                if(input!=null){
                    input.close();
                }
                if(output!=null){
                    output.close();
                }
                if(reqConnection!=null){
                    reqConnection.disconnect();
                }
            } catch (Exception ex) {
                logger.info("IO流关闭异常",ex);
            }
        }
        return returnJson;
    }
}
